package com.ry.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.util.AttributeSet;
import android.util.Log;
import android.view.animation.LinearInterpolator;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;

/**
 * 水波纹
 *
 * Create by renxianzuo on 2021/4/15
 * Describe
 */
public class MyRippleView extends ConstraintLayout {
    private ValueAnimator animator;
    float ratio = 0;//0～1
    private Paint mPaint;//画笔

    public MyRippleView(@NonNull Context context) {
        super(context);
        initPaint(context);
    }

    public MyRippleView(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initPaint(context);
    }

    public MyRippleView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initPaint(context);
    }

    public MyRippleView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        initPaint(context);
    }

    private void initPaint(Context context) {
        setWillNotDraw(false);

        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL);
        mPaint.setAntiAlias(true);

        startAnimator();
    }

    @Override
    protected void onDraw(Canvas canvas) {

        canvas.save();
        mPaint.setColor(Color.argb((int)(0xff*(1 - ratio)),0x6c,0xab,0xec));
        canvas.drawCircle(getWidth()/2,getHeight()/2,getHeight() / 2 * ratio,mPaint);
        canvas.restore();

        super.onDraw(canvas);
    }

    void startAnimator() {
        if(animator == null) {
            animator = ValueAnimator.ofFloat(0f, 1f);
            animator.setDuration(5000);
            animator.setRepeatCount(Integer.MAX_VALUE - 1);
            animator.setInterpolator(new LinearInterpolator());
            animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
                @Override
                public void onAnimationUpdate(ValueAnimator animation) {
                    // 获取到动画每次该变得float值，赋值给xpoint
                    ratio = (Float) animation.getAnimatedValue();
                    // 通知view重绘
                    invalidate();
                }
            });
        }
        animator.start();
    }

    void stopAnimator(){
        if(animator != null){
            animator.end();
            animator = null;
        }
    }
}
